<?php
/**
 * Created by PhpStorm.
 * User: wanyihua
 * Date: 2017/1/9
 * Time: 14:56
 */
namespace app\api\model\dao;

use app\library\Flag;
use think\Model;
use think\Db;

class Coupon extends Model
{
    protected $table = 'coupon';
    protected $pk = 'coupon_id';
    protected $autoWriteTimestamp = true;//自动写入create_time和update_time的时间戳字段

    /**
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getCouponList()
    {
        $field = 'create_time, update_time';
        return Db::table($this->table)->field($field, true)->select();
    }

    /**
     * @param $coupon_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getCouponById($coupon_id)
    {
        $conds = array(
            'coupon_id' => $coupon_id,
            'status' => Flag::COUPON_STATUS_VALID,
        );
        $field = 'create_time, update_time';

        return Db::table($this->table)->where($conds)->field($field, true)->find();
    }

    /**
     * @param $coupon_id
     * @return false|int
     *  停用优惠券
     */
    public function stopUserCoupon($coupon_id)
    {
        $conds = array(
            'coupon_id' => $coupon_id,
        );
        $field = [
            'status' => Flag::COUPON_STATUS_INVALID
        ];
        return $this->isUpdate(true)->allowField(true)->save($field, $conds);
    }

    /**
     * @param $coupon_id
     * @return int|true
     * @throws \think\Exception
     * 减少优惠券数量
     */
    public function decreaseRemained($coupon_id)
    {
        $conds = [
            'coupon_id' => $coupon_id
        ];
        return $this->where($conds)->setDec('amount_remained');
        //$sql = sprintf("update %s set amount_remained=amount_remained-1,update_time=%s where coupon_id=%d", $this->table, $coupon_id, time());
        //return Db::execute($sql);
        //return $this->isUpdate(true)->allowField(true)->save($field,$conds);
    }

    /**
     * @param $param
     * @return false|int
     */
    public function addCoupon($param)
    {
        $param['create_time'] = time();
        $this->data($param);
        return $this->allowField(true)->save();
    }
}